package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.util.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.PipedReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuanziService {

    @Reference
    private PublishApi publishApi;

    @Autowired
    private OssTemplate ossTemplate;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void publishMovements(Publish publish, MultipartFile[] imageContent) throws IOException {

        // 1、指定用户id
        publish.setUserId(UserHolder.getUserId());
        // 2、默认审核通过
        publish.setState(1); // TODO  后期加了华为云审核（文件+图片），这边修改

        // 3、将图片上传到阿里云OSS
        List<String> medias = new ArrayList<>();
        if (imageContent != null) {
            for (MultipartFile file : imageContent) {
                String imgUrl = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
                medias.add(imgUrl);
            }
            // 将图片路径设置到publish中
            publish.setMedias(medias);
        }

        // 4、调用api保存动态
        publishApi.save(publish);

    }

    public ResponseEntity findAlbumByPage(Integer pageNum, Integer pageSize, Long userId) {
        //调用api查询动态分页对象
        PageBeanVo pageBeanVo=publishApi.findAlbumByPage(pageNum,pageSize,userId);
        //便利动态详情  封装publishVo
        List<PublishVo> voList =new ArrayList<>();
        List<Publish> publishList= (List<Publish>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(publishList)) {
            for (Publish publish :publishList){
                PublishVo vo = new PublishVo();
                //根据用户id查询userInfo
                UserInfo userInfo=userInfoApi.fingByUserId(publish.getUserId());
                //封装userInfo到vo中
                BeanUtils.copyProperties(userInfo,vo);
                if (StrUtil.isNotEmpty(userInfo.getTags())) {
                    vo.setTags(userInfo.getTags().split(","));  //用户标签
                }
                //封装道publish道vo中
                BeanUtils.copyProperties(publish,vo);
                if (CollectionUtil.isNotEmpty(publish.getMedias())) {
                    vo.setImageContent(publish.getMedias().toArray(new String[]{}));  //动态图片
                }
                vo.setCreateDate(RelativeDateFormat.format(new Date(publish.getUserId())));  //动态图片的发布时间
                vo.setDistance("距离1.2公里");
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findTimeLineByPage(Integer pageNum, Integer pageSize) {
        // 查询动态详情
        PageBeanVo pageBeanVo =publishApi.findTimeLineByPage(pageNum,pageSize,UserHolder.getUserId());
        List<PublishVo> voList =new ArrayList<>();
        List<Publish> publishList = (List<Publish>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(publishList)) {
            for (Publish publish : publishList) {
                PublishVo vo = new PublishVo();
                //userInfo 封装到vo
                UserInfo userInfo = userInfoApi.fingByUserId(publish.getUserId());
                vo.setUserInfo(userInfo);
                //publish 封装到vo
                vo.setPublish(publish);
                // 是否点赞
                if (stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUserId(), publish.getId()))) {
                    vo.setHasLiked(1);
                } else {
                    vo.setHasLiked(0);
                }// 0 是未点赞  1 是点赞
                // 将vo  加入集合中
                voList.add(vo);

            }

        }
        //分页使用voList
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findRecommendByPage(Integer pageNum, Integer pageSize) {
        //调用api 查询动态详情
        PageBeanVo pageBeanVo =publishApi.findRecommendByPage(pageNum,pageSize,UserHolder.getUserId());
        List<PublishVo> voList =new ArrayList<>();
        List<Publish> publishList= (List<Publish>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(publishList)) {
            for (Publish publish : publishList){
                PublishVo vo= new PublishVo();
                //userInfo封装vo
                UserInfo userInfo=userInfoApi.fingByUserId(publish.getUserId());
                vo.setUserInfo(userInfo);
                //将publish 封装vo
                vo.setPublish(publish);
                //是否点赞
                if (stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}", UserHolder.getUserId(), publish.getId()))) {
                    vo.setHasLiked(1);
                } else {
                    vo.setHasLiked(0);
                }
                // 是否喜欢
                if (stringRedisTemplate.hasKey(StrUtil.format("publish_love_comment_{}_{}", UserHolder.getUserId(), publish.getId()))) {
                    vo.setHasLoved(1);
                } else {
                    vo.setHasLoved(0);
                }
                // 将vo封装到集合中
                voList.add(vo);

            }
        }
        //将voList 添加到pageBean
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }
   // 好友点赞
    public ResponseEntity likePublish(String publishId) {
        //调用api 保存comment 对象
        Comment comment =new Comment();
        comment.setPublishId(new ObjectId(publishId));  //指定动态id
        comment.setUserId(UserHolder.getUserId());  // 指定点赞人
        comment.setCommentType(1);  // 评论类型  1 点赞
        comment.setPubType(1);//动态类型  动态 小视频 评论
        Integer total = commentApi.save(comment);
        //想redis中储存对此动态的点赞记录
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_like_comment_{}_{}",
                UserHolder.getUserId(), publishId), "1");
        return ResponseEntity.ok(total);
    }
    //推荐点赞
    public ResponseEntity dislikePublish(String publishId) {
        //调用api 删除点赞记录
        Comment comment=new Comment();
        comment.setUserId(UserHolder.getUserId());  // 用户的id
        comment.setPublishId(new ObjectId(publishId));  // 动态id
        comment.setCommentType(1); //点赞
        Integer total =commentApi.remove(comment);
        // 删除redis中缓存
        stringRedisTemplate.delete(StrUtil.format("publish_like_comment_{}_{}",UserHolder.getUserId(),publishId));
        return ResponseEntity.ok(total);
    }

    public ResponseEntity lovePublish(String publishId) {
        // 创建comment  对象
        Comment comment=new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3); //评论类型  点赞 评论  喜欢
        comment.setPubType(1);  //动态类型  圈子 视频 评论
        // 保存并返回点赞数量
        Integer total =commentApi.save(comment);
        // 将点赞储存到redis 中
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_love_comment_{}_{}", UserHolder.getUserId(), publishId), "1");
        return ResponseEntity.ok(total);
    }

    public ResponseEntity unlovePublish(String publishId) {
        //创建comment 对象 设置删除属性
        Comment comment =new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);

        //调用api删除
        Integer tobal =commentApi.remove(comment);
        // 删除redis中的缓存
        stringRedisTemplate.delete(StrUtil.format("publish_love_comment_{}_{}",UserHolder.getUserId(),publishId));
        return  ResponseEntity.ok(tobal);


    }
        //单条评论
    public ResponseEntity findPublishVoById(String publishId) {
        // 调用api 查询
        Publish publish =publishApi.findById(publishId);
        // userInfo +publish =vo
        PublishVo vo =new PublishVo();
        UserInfo userInfo=userInfoApi.fingByUserId(publish.getUserId());
        vo.setUserInfo(userInfo);
        vo.setPublish(publish);
        return ResponseEntity.ok(vo);
    }
}